//
//  ComposeViewController.swift
//  sinazd
//
//  Created by apple on 16/3/16.
//  Copyright © 2016年 apple. All rights reserved.
//

//类扩展只能增加方法 无法增加成员属性，所以，懒加载的属性都在类本身中添加


import UIKit
import SVProgressHUD
import SnapKit
import AFNetworking

class ComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
 
        setupUI()
        registerNotification()
    }
    
  
    
    func keyboardChange(n:NSNotification) {
        
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        let offset = -ScreenHeight + rect.origin.y
        
        UIView.animateWithDuration(duration) { () -> Void in
            
            self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(self.view.snp_bottom).offset(offset)
            })
            self.view.layoutIfNeeded()
            
        }
        
    }
    
    //注册通知中心
    private func registerNotification() {
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //懒加载View界面的控件
    private lazy var textView:UITextView = {
        
        let tv = UITextView()
        
        tv.textColor = UIColor.darkGrayColor()
        tv.font = UIFont.systemFontOfSize(18)
        tv.backgroundColor = UIColor.yellowColor()
        
        tv.delegate = self
        
        //设置textView的隐藏键盘
        tv.keyboardDismissMode = .OnDrag
        tv.alwaysBounceVertical = true
        
        return tv
        
    }()
    
    //占位label
    private lazy var placeHolderLabel = UIFactory.labelWith("人道酬诚", textColor: UIColor.lightGrayColor(), fontSize: 18)
    
    //底部工具条
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    //图片选择控制器
    private lazy var pictureSelectorVC:PictureSelectorController = PictureSelectorController()
    
    
}







extension ComposeViewController {
    
    //设置View界面
    func setupUI() {
        
        view.backgroundColor = UIColor.blueColor()
        
        setNav()
        
        setTextView()
        
        
        setToolBar()
        
        
        setPictureSelector()
        
        self.view.bringSubviewToFront(toolBar)
    }
    
    //设置底部工具条
    func setToolBar() {
        
        view.addSubview(toolBar)
       
        
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(self.view)
        }
        
        var items = [UIBarButtonItem]()
        
        
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background"]]

        for item in itemSettings {
            
            let imageName = item["imageName"]
            let btn = UIFactory.buttonWithImage(imageName, backImageName: nil)
            if let actionName = item["actionName"] {
                btn.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside)
            }
            
            let barItem = UIBarButtonItem(customView: btn)
            
            
            
            items.append(barItem)
            
            let place = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            
            items.append(place)
            
        }
        
        items.removeLast()
        
        toolBar.items = items
        
       
    }
    
    //点击图片和表情的按钮事件
    @objc private func selectPicture() {
        
        
        UIView.animateWithDuration(0.25) { () -> Void in
            //在这里，实现选择控制器view的高度由0变成三分之二屏幕高
            self.pictureSelectorVC.view.snp_updateConstraints(closure: { (make) -> Void in
                
                if self.pictureSelectorVC.view.frame.height == 0 {
                
                make.height.equalTo(ScreenHeight / 3 * 2)
                    
                }else{
                    
                    make.height.equalTo(0)
                    
                }
                
            })
                   
            self.view.layoutIfNeeded()
            
        }
        
    }
    
    @objc private func selectEmoticon() {
        __FUNCTION__
    }
    
    
    func setPictureSelector() {
        
        self.addChildViewController(pictureSelectorVC)
        self.view.addSubview(pictureSelectorVC.view)
        
        pictureSelectorVC.view.snp_makeConstraints { (make) -> Void in
            
            make.bottom.left.right.equalTo(self.view)
            make.height.equalTo(0)
            
        }
        
    }
    
    
    func setTextView() {
        
        view.addSubview(textView)
        
        textView.snp_makeConstraints { (make) -> Void in
            
            make.left.top.right.equalTo(self.view)
            
            make.height.equalTo(ScreenHeight / 3)
        }
        
        
        //添加占位label
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
            
        }
        
    }
    
    

    
    
    //设置导航栏
    func setNav() {
       
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        
      //自定义导航栏lableView
        let myView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        
        navigationItem.titleView = myView
        
        
        let titleLabel = UIFactory.labelWith("发布微博", textColor: UIColor.darkGrayColor(), fontSize: 18)
        let nameLabel = UIFactory.labelWith(UserAccount.sharedAccount.name ?? "", textColor: UIColor.lightGrayColor(), fontSize: 14)
        myView.addSubview(titleLabel)
        myView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(myView.snp_top)
            make.centerX.equalTo(myView.snp_centerX)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(myView.snp_bottom)
            make.centerX.equalTo(myView.snp_centerX)
        }
        
    }
 
    
    
    
    //导航栏item的点击事件
    @objc private func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    @objc private func send() {
        
        
        guard let token = UserAccount.sharedAccount.access_token else {
         
            SVProgressHUD.showErrorWithStatus("网络请求失败")
            return
        }
        
        let parameters = ["access_token":token,"status":textView.text]
        
        if pictureSelectorVC.imageList.count == 0{
    
        let urlString = "https://api.weibo.com/2/statuses/update.json"

        HTTPClient.sharedHTTPClient.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            
            if error != nil {
                
                SVProgressHUD.showErrorWithStatus("网络请求失败")
                
            }
            
            SVProgressHUD.showSuccessWithStatus("发布成功")
            self.close()
            
        }
        }else{
            
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            HTTPClient.sharedHTTPClient.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                
                //遍历所有图片，添加到formData
                for image in self.pictureSelectorVC.imageList {
                    
                    let data = UIImagePNGRepresentation(image)!
                    
                    formData.appendPartWithFileData(data, name: "pic", fileName: "ssdaf", mimeType: "application/octet-stream")
                    
                }
                
                }, progress: nil, success: { (_, result) -> Void in
                    
                    print(result)
                    
                }, failure: { (_, error) -> Void in
                    
                    print(error)
            })
            
            
            
        }
    
    }
    
}


extension ComposeViewController : UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        
        placeHolderLabel.hidden = textView.hasText()
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
}

